/**
 * 中国9号健康产业有限公司
 * Copyright (C) JiuHaoHealth Corporation. All Rights Reserved
 */
package com.jiuhaohealth.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

/**
 * @author minghui(jackchenmh@gmail.com)
 * @version 2014-3-18 下午5:08:45
 */
public class JiuHaoBeanUtils {

	public static <T> T mapToBean(Map<String, Object> params , Class<T> beanClass) {
		//生成Bean
		Map<String, Object> new_params = null;
		try{
			new_params = params;
			T bean = beanClass.newInstance();
			BeanUtils.populate(bean, new_params);
			return bean;
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	public static Map<String, Object> beanToMap(Object obj) {
		try {
			return BeanUtils.describe(obj);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Object byteToObject(byte[] bytes) {
        Object obj = null;
        try {
	        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
	        ObjectInputStream oi = new ObjectInputStream(bi);
	
	        obj = oi.readObject();

	        oi.close();
	        bi.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
	
	public static byte[] objectToByte(java.lang.Object obj) {
        byte[] bytes = null;
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(obj);

            bytes = bo.toByteArray();

            oo.close(); 
            bo.close();   
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return(bytes);
    }

}
